var aesjs = require('aes-js');
var crypto = require('crypto');

function fnGeneralKeyIV(key, callback) {
    var buf = new Buffer(key, "utf8");
    var _key = crypto.createHash('sha256').update(buf).digest();
    var _iv = crypto.createHash('md5').update(buf).digest();

    callback && callback(_key, _iv);
}

var aesCode = {
    algorithm: "aes-256-cbc",
    cipherEncoding: "base64",
    encrypt: function (key, val) {
        var self = this;
        var cipher = undefined;
        fnGeneralKeyIV(key, function (_key, _iv) {
            cipher = new aesjs.ModeOfOperation.cbc(_key, _iv);
        });
        var buf = new Buffer(val, "utf8");
        var bytes = new Buffer(16);

        bytes.forEach((_byte, x) => {
            if (x < buf.length)
                bytes[x] = buf[x];
            else bytes[x] = 16 - buf.length;
        });

        var result = cipher.encrypt(bytes);

        return new Buffer(result).toString(self.cipherEncoding);
    },
    decrypt: function (key, val) {
        var self = this;
        var cipher = undefined;
        fnGeneralKeyIV(key, function (_key, _iv) {
            cipher = new aesjs.ModeOfOperation.cbc(_key, _iv);
        });
        var buf = new Buffer(val, self.cipherEncoding);
        var result = cipher.decrypt(buf);

        var bytes = new Buffer(16);
        result.forEach((_byte, x) => {
            if (_byte < 16)
                bytes[x] = 0;
            else bytes[x] = _byte;
        });

        return aesjs.utils.utf8.fromBytes(bytes);
    }
};

module.exports = aesCode;